<template>
  <div class="customer-approval">
    <div class="page-header">
      <h2>客户审批管理</h2>
      <p>管理客户申请审批流程，包括待审批、历史审批和我发起的申请</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card stats-primary">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.totalApplications || 0 }}</h3>
                <p>总申请数</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <User />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-warning">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.pendingApprovals || 0 }}</h3>
                <p>待审批</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Clock />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-success">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.approvedApplications || 0 }}</h3>
                <p>已通过</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Check />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-danger">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.rejectedApplications || 0 }}</h3>
                <p>已拒绝</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Close />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-tabs v-model="activeTab" class="approval-tabs">
      <!-- 待审批 -->
      <el-tab-pane label="待审批" name="pending">
        <div class="tab-content">
          <div class="toolbar">
            <el-button type="primary" @click="refreshPendingList">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="batchApprove" :disabled="selectedPendingItems.length === 0">
              <el-icon><Check /></el-icon>
              批量审批
            </el-button>
          </div>
          
          <el-table
            :data="pendingList"
            v-loading="pendingLoading"
            @selection-change="handlePendingSelectionChange"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="客户ID" width="80" align="center" />
            <el-table-column prop="customerName" label="客户名称" width="150" show-overflow-tooltip />
            <el-table-column prop="contactPerson" label="联系人" width="100" />
            <el-table-column prop="phone" label="联系电话" width="130" />
            <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
            <el-table-column prop="industry" label="行业" width="100" />
            <el-table-column prop="customerCode" label="客户代码" width="120" />
            <el-table-column prop="approvalStatus" label="审批状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getApprovalStatusTag(scope.row.approvalStatus)">
                  {{ getApprovalStatusName(scope.row.approvalStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentStep" label="当前步骤" width="120" show-overflow-tooltip />
            <el-table-column prop="currentApprover" label="当前审批人" width="120" />
            <el-table-column prop="processInstanceId" label="流程实例ID" width="150" show-overflow-tooltip />
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="流程进度" width="200">
              <template #default="scope">
                <div class="process-progress">
                  <div class="progress-steps">
                    <div 
                      v-for="(step, index) in getProcessSteps(scope.row)"
                      :key="index"
                      class="progress-step"
                      :class="step.status"
                    >
                      <div class="step-circle">
                        <el-icon v-if="step.status === 'completed'">
                          <Check />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'current'">
                          <Loading />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'rejected'">
                          <Close />
                        </el-icon>
                        <span v-else>{{ index + 1 }}</span>
                      </div>
                      <div class="step-name">{{ step.name }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">查看详情</el-button>
                <el-button size="small" type="success" @click="approve(scope.row)">审批</el-button>
                <el-button size="small" type="danger" @click="reject(scope.row)">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="pendingPagination.currentPage"
              v-model:page-size="pendingPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pendingPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handlePendingSizeChange"
              @current-change="handlePendingCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <!-- 历史已审批 -->
      <el-tab-pane label="历史已审批" name="history">
        <div class="tab-content">
          <div class="toolbar">
            <el-form :inline="true" :model="historySearchForm" class="search-form">
              <el-form-item label="客户名称">
                <el-input v-model="historySearchForm.customerName" placeholder="请输入客户名称" clearable />
              </el-form-item>
              <el-form-item label="审批结果">
                <el-select v-model="historySearchForm.approvalResult" placeholder="请选择审批结果" clearable>
                  <el-option label="已通过" value="APPROVED" />
                  <el-option label="已拒绝" value="REJECTED" />
                </el-select>
              </el-form-item>
              <el-form-item label="审批时间">
                <el-date-picker
                  v-model="historySearchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchHistory">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="resetHistorySearch">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            :data="historyList"
            v-loading="historyLoading"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="客户ID" width="80" align="center" />
            <el-table-column prop="customerName" label="客户名称" width="150" show-overflow-tooltip />
            <el-table-column prop="contactPerson" label="联系人" width="100" />
            <el-table-column prop="phone" label="联系电话" width="130" />
            <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
            <el-table-column prop="industry" label="行业" width="100" />
            <el-table-column prop="customerCode" label="客户代码" width="120" />
            <el-table-column prop="approvalStatus" label="审批状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getApprovalStatusTag(scope.row.approvalStatus)">
                  {{ getApprovalStatusName(scope.row.approvalStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentStep" label="当前步骤" width="120" show-overflow-tooltip />
            <el-table-column prop="currentApprover" label="当前审批人" width="120" />
            <el-table-column prop="processInstanceId" label="流程实例ID" width="150" show-overflow-tooltip />
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="流程进度" width="200">
              <template #default="scope">
                <div class="process-progress">
                  <div class="progress-steps">
                    <div 
                      v-for="(step, index) in getProcessSteps(scope.row)"
                      :key="index"
                      class="progress-step"
                      :class="step.status"
                    >
                      <div class="step-circle">
                        <el-icon v-if="step.status === 'completed'">
                          <Check />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'current'">
                          <Loading />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'rejected'">
                          <Close />
                        </el-icon>
                        <span v-else>{{ index + 1 }}</span>
                      </div>
                      <div class="step-name">{{ step.name }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="historyPagination.currentPage"
              v-model:page-size="historyPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="historyPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleHistorySizeChange"
              @current-change="handleHistoryCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <!-- 我发起的申请 -->
      <el-tab-pane label="我发起的申请" name="myApplications">
        <div class="tab-content">
          <div class="toolbar">
            <el-form :inline="true" :model="myApplicationsSearchForm" class="search-form">
              <el-form-item label="客户名称">
                <el-input v-model="myApplicationsSearchForm.customerName" placeholder="请输入客户名称" clearable />
              </el-form-item>
              <el-form-item label="审批状态">
                <el-select v-model="myApplicationsSearchForm.approvalStatus" placeholder="请选择状态" clearable>
                  <el-option label="待审批" value="PENDING" />
                  <el-option label="审批中" value="APPROVING" />
                  <el-option label="已通过" value="APPROVED" />
                  <el-option label="已拒绝" value="REJECTED" />
                </el-select>
              </el-form-item>
              <el-form-item label="申请时间">
                <el-date-picker
                  v-model="myApplicationsSearchForm.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchMyApplications">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="resetMyApplicationsSearch">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
            <div class="toolbar-right">
              <el-button type="primary" @click="createNewApplication">
                <el-icon><Plus /></el-icon>
                新建申请
              </el-button>
            </div>
          </div>

          <el-table
            :data="myApplicationsList"
            v-loading="myApplicationsLoading"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="客户ID" width="100" />
            <el-table-column prop="customerName" label="客户名称" width="150" />
            <el-table-column prop="contactPerson" label="联系人" width="120" />
            <el-table-column prop="phone" label="联系电话" width="130" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="industry" label="行业" width="120" />
            <el-table-column prop="customerCode" label="客户代码" width="120" />
            <el-table-column prop="approvalStatus" label="审批状态" width="100">
              <template #default="scope">
                <el-tag :type="getApprovalStatusTag(scope.row.approvalStatus)">
                  {{ getApprovalStatusName(scope.row.approvalStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentStep" label="当前步骤" width="150">
              <template #default="scope">
                <el-tag :type="getApprovalStepTag(scope.row.currentStep)">
                  {{ getApprovalStepName(scope.row.currentStep) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentApprover" label="当前审批人" width="120" />
            <el-table-column prop="processInstanceId" label="流程实例ID" width="150" />
            <el-table-column prop="createdAt" label="创建时间" width="160" />
            <el-table-column label="流程进度" width="200">
              <template #default="scope">
                <div class="process-progress">
                  <div class="progress-steps">
                    <div 
                      v-for="(step, index) in getProcessSteps(scope.row)"
                      :key="index"
                      class="progress-step"
                      :class="step.status"
                    >
                      <div class="step-circle">
                        <el-icon v-if="step.status === 'completed'">
                          <Check />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'current'">
                          <Loading />
                        </el-icon>
                        <el-icon v-else-if="step.status === 'rejected'">
                          <Close />
                        </el-icon>
                        <span v-else>{{ index + 1 }}</span>
                      </div>
                      <div class="step-name">{{ step.name }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewDetail(scope.row)">查看详情</el-button>
                <el-button size="small" @click="viewProcessSteps(scope.row)">流程进度</el-button>
                <el-button 
                  v-if="isOfficeBusiness()"
                  size="small" 
                  type="warning" 
                  @click="editApplication(scope.row)"
                  :disabled="scope.row.approvalStatus !== 'PENDING'"
                >
                  编辑
                </el-button>
                <el-button 
                  v-if="isOfficeBusiness()"
                  size="small" 
                  type="success" 
                  @click="submitApplication(scope.row)"
                  :disabled="scope.row.approvalStatus !== 'PENDING' || scope.row.processInstanceId"
                >
                  提交审批
                </el-button>
                <el-button 
                  v-if="isOfficeBusiness()"
                  size="small" 
                  type="danger" 
                  @click="cancelApplication(scope.row)"
                  :disabled="scope.row.approvalStatus !== 'PENDING'"
                >
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="myApplicationsPagination.currentPage"
              v-model:page-size="myApplicationsPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="myApplicationsPagination.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleMyApplicationsSizeChange"
              @current-change="handleMyApplicationsCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 流程进度查看对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="客户审批流程进度"
      width="900px"
      @close="handleProcessDialogClose"
    >
      <CustomerProcessDiagram
        :current-status="selectedRecord?.approvalStatus || selectedRecord?.status"
        :current-step="selectedRecord?.approvalStep || selectedRecord?.currentStep"
        :approval-result="selectedRecord?.approvalResult"
        :process-instance-id="selectedRecord?.processInstanceId"
      />
    </el-dialog>


    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="客户详情"
      width="900px"
    >
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="客户代码">{{ currentDetail.customerCode }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentDetail.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentDetail.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentDetail.email }}</el-descriptions-item>
          <el-descriptions-item label="行业">{{ currentDetail.industry }}</el-descriptions-item>
          <el-descriptions-item label="审批状态">
            <el-tag :type="getApprovalStatusTag(currentDetail.approvalStatus)">
              {{ getApprovalStatusName(currentDetail.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前步骤">{{ currentDetail.currentStep }}</el-descriptions-item>
          <el-descriptions-item label="当前审批人">{{ currentDetail.currentApprover }}</el-descriptions-item>
          <el-descriptions-item label="流程实例ID">{{ currentDetail.processInstanceId }}</el-descriptions-item>
          <el-descriptions-item label="创建人">{{ currentDetail.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentDetail.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新人">{{ currentDetail.updateBy }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(currentDetail.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="拒绝原因" :span="2" v-if="currentDetail.rejectReason">
            {{ currentDetail.rejectReason }}
          </el-descriptions-item>
          <el-descriptions-item label="拒绝步骤" v-if="currentDetail.rejectStep">
            {{ currentDetail.rejectStep }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2" v-if="currentDetail.remarks">
            {{ currentDetail.remarks }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 流程步骤对话框 -->
    <el-dialog
      v-model="processStepsDialogVisible"
      title="审批流程进度"
      width="900px"
    >
      <div class="process-steps-content">
        <div class="process-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="客户名称">{{ currentProcessDetail.customerName }}</el-descriptions-item>
            <el-descriptions-item label="流程实例ID">{{ currentProcessDetail.processInstanceId }}</el-descriptions-item>
            <el-descriptions-item label="当前状态">{{ getApprovalStatusName(currentProcessDetail.approvalStatus) }}</el-descriptions-item>
            <el-descriptions-item label="当前步骤">{{ getApprovalStepName(currentProcessDetail.currentStep) }}</el-descriptions-item>
            <el-descriptions-item label="当前审批人">{{ currentProcessDetail.currentApprover }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentProcessDetail.createdAt }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="steps-timeline">
          <h4>审批流程步骤</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(step, index) in processSteps"
              :key="step.id"
              :timestamp="step.completedTime || '待处理'"
              :type="getStepTimelineType(step.status)"
              :icon="getStepIcon(step.status)"
            >
              <div class="step-content">
                <div class="step-title">{{ step.name }}</div>
                <div class="step-role">角色：{{ getRoleName(step.role) }}</div>
                <div class="step-approver" v-if="step.approverName">
                  审批人：{{ step.approverName }}
                </div>
                <div class="step-comment" v-if="step.comment">
                  审批意见：{{ step.comment }}
                </div>
                <div class="step-result" v-if="step.result">
                  审批结果：<el-tag :type="getApprovalResultTag(step.result)">
                    {{ getApprovalResultName(step.result) }}
                  </el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, 
  Check, 
  Search, 
  Plus,
  View,
  Edit,
  Delete,
  User,
  Clock,
  Close,
  Loading
} from '@element-plus/icons-vue'
import CustomerProcessDiagram from '../../components/CustomerProcessDiagram.vue'
import { 
  getPendingCustomerApplications,
  approveCustomer,
  rejectCustomer,
  getCustomerApprovalHistory,
  getUserCustomerApplications,
  submitCustomerApplication,
  cancelCustomerApplication,
  getByCreateBy,
  getHistoryCustomerApplications
} from '../../api/customer.js'

export default {
  name: 'CustomerApproval',
  components: {
    Refresh,
    Check,
    Search,
    Plus,
    View,
    Edit,
    Delete,
    User,
    Clock,
    Close,
    Loading,
    CustomerProcessDiagram
  },
  setup() {
    // 当前激活的标签页
    const activeTab = ref('pending')
    
    // 统计数据
    const statistics = ref({
      totalApplications: 0,
      pendingApprovals: 0,
      approvedApplications: 0,
      rejectedApplications: 0
    })
    
    // 待审批列表 - 基于CustomerApprovalRecord
    const pendingList = ref([])
    const pendingLoading = ref(false)
    const selectedPendingItems = ref([])
    const pendingPagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 历史审批列表 - 基于CustomerApprovalRecord
    const historyList = ref([])
    const historyLoading = ref(false)
    const historySearchForm = reactive({
      customerName: '',
      approvalResult: '',
      dateRange: []
    })
    const historyPagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 我发起的申请列表 - 基于customer_basic_info
    const myApplicationsList = ref([])
    const myApplicationsLoading = ref(false)
    const myApplicationsSearchForm = reactive({
      customerName: '',
      approvalStatus: '',
      dateRange: []
    })
    const myApplicationsPagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 获取当前登录用户
    const getCurrentUser = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        return JSON.parse(userInfoStr)
      }
      return null
    }
    
    // 检查当前用户是否为office_business
    const isOfficeBusiness = () => {
      const user = getCurrentUser()
      return user && user.username === 'office_business'
    }

    // 审批流程步骤定义 - 对应NewCustomer.bpmn20.xml
    const approvalSteps = ref([
      { id: 'taskFillInfo', name: '销售员填写客户资料', role: 'SALES', status: 'pending' },
      { id: 'taskManagerApprove', name: '地区经理审批', role: 'REGIONAL_MANAGER', status: 'pending' },
      { id: 'taskDirectorApprove', name: '大区经理审批', role: 'AREA_MANAGER', status: 'pending' },
      { id: 'taskCreditControl', name: '信用控制组审批', role: 'CREDIT_CONTROL', status: 'pending' },
      { id: 'taskSalesDirector', name: '销售总监审批', role: 'SALES_DIRECTOR', status: 'pending' },
      { id: 'taskBusinessConfirm', name: '公司商务人员审核', role: 'BUSINESS', status: 'pending' }
    ])

    // 流程进度对话框
    const processDialogVisible = ref(false)
    const selectedRecord = ref(null)
    

    // 详情对话框
    const detailDialogVisible = ref(false)
    const currentDetail = ref({})

    // 流程步骤对话框
    const processStepsDialogVisible = ref(false)
    const currentProcessDetail = ref({})
    const processSteps = ref([])

    // 获取审批步骤标签样式
    const getApprovalStepTag = (step) => {
      const stepMap = {
        'taskFillInfo': 'info',
        'taskManagerApprove': 'warning',
        'taskDirectorApprove': 'primary',
        'taskCreditControl': 'success',
        'taskSalesDirector': 'danger',
        'taskBusinessConfirm': 'success'
      }
      return stepMap[step] || 'info'
    }

    // 获取审批步骤名称
    const getApprovalStepName = (step) => {
      const stepNameMap = {
        'taskFillInfo': '销售员填写客户资料',
        'taskManagerApprove': '地区经理审批',
        'taskDirectorApprove': '大区经理审批',
        'taskCreditControl': '信用控制组审批',
        'taskSalesDirector': '销售总监审批',
        'taskBusinessConfirm': '公司商务人员审核'
      }
      return stepNameMap[step] || step
    }

    // 获取角色标签样式
    const getRoleTag = (role) => {
      const roleMap = {
        'SALES': 'info',
        'REGIONAL_MANAGER': 'warning',
        'AREA_MANAGER': 'primary',
        'CREDIT_CONTROL': 'success',
        'SALES_DIRECTOR': 'danger',
        'BUSINESS': 'success',
        'ADMIN': 'info',
        'MANAGER': 'warning',
        'TECH_REVIEWER': 'primary',
        'ENV_REVIEWER': 'success'
      }
      return roleMap[role] || 'info'
    }

    // 获取角色名称
    const getRoleName = (role) => {
      const roleNameMap = {
        'SALES': '销售员',
        'REGIONAL_MANAGER': '地区经理',
        'AREA_MANAGER': '大区经理',
        'CREDIT_CONTROL': '信用控制组',
        'SALES_DIRECTOR': '销售总监',
        'BUSINESS': '商务人员',
        'ADMIN': '管理员',
        'MANAGER': '经理',
        'TECH_REVIEWER': '技术审核员',
        'ENV_REVIEWER': '环境审核员'
      }
      return roleNameMap[role] || role
    }

    // 获取审批结果标签样式
    const getApprovalResultTag = (result) => {
      const resultMap = {
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'PENDING': 'warning'
      }
      return resultMap[result] || 'info'
    }

    // 获取审批结果名称
    const getApprovalResultName = (result) => {
      const resultNameMap = {
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'PENDING': '待审批'
      }
      return resultNameMap[result] || result
    }

    // 获取审批状态标签样式
    const getApprovalStatusTag = (status) => {
      const statusMap = {
        'PENDING': 'info',
        'APPROVING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger'
      }
      return statusMap[status] || 'info'
    }

    // 获取审批状态名称
    const getApprovalStatusName = (status) => {
      const statusNameMap = {
        'PENDING': '待审批',
        'APPROVING': '审批中',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusNameMap[status] || status
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString()
    }

    // 获取步骤时间线类型
    const getStepTimelineType = (status) => {
      const typeMap = {
        'completed': 'success',
        'current': 'primary',
        'pending': 'info',
        'rejected': 'danger'
      }
      return typeMap[status] || 'info'
    }

    // 获取步骤图标
    const getStepIcon = (status) => {
      const iconMap = {
        'completed': 'Check',
        'current': 'Clock',
        'pending': 'Clock',
        'rejected': 'Close'
      }
      return iconMap[status] || 'Clock'
    }

    // 处理待审批选择变化
    const handlePendingSelectionChange = (selection) => {
      selectedPendingItems.value = selection
    }

    // 刷新待审批列表
    const refreshPendingList = async () => {
      try {
        pendingLoading.value = true
        const response = await getPendingCustomerApplications()
        pendingList.value = response || []
        pendingPagination.total = pendingList.value.length
      } catch (error) {
        console.error('加载待审批列表失败:', error)
        ElMessage.error('加载待审批列表失败')
        pendingList.value = []
      } finally {
        pendingLoading.value = false
      }
    }

    // 搜索历史审批
    const searchHistory = async () => {
      try {
        historyLoading.value = true
        const response = await getHistoryCustomerApplications()
        historyList.value = response || []
        historyPagination.total = historyList.value.length
      } catch (error) {
        console.error('加载历史审批失败:', error)
        ElMessage.error('加载历史审批失败')
        historyList.value = []
      } finally {
        historyLoading.value = false
      }
    }

    // 重置历史搜索
    const resetHistorySearch = () => {
      Object.assign(historySearchForm, {
        customerName: '',
        approvalResult: '',
        dateRange: []
      })
      searchHistory()
    }

    // 搜索我的申请
    const searchMyApplications = async () => {
      try {
        myApplicationsLoading.value = true
        const response = await getByCreateBy()
        myApplicationsList.value = response || []
        myApplicationsPagination.total = myApplicationsList.value.length
      } catch (error) {
        console.error('加载我的申请失败:', error)
        ElMessage.error('加载我的申请失败')
        myApplicationsList.value = []
      } finally {
        myApplicationsLoading.value = false
      }
    }

    // 重置我的申请搜索
    const resetMyApplicationsSearch = () => {
      Object.assign(myApplicationsSearchForm, {
        customerName: '',
        approvalStatus: '',
        dateRange: []
      })
      searchMyApplications()
    }

    // 查看详情
    const viewDetail = (row) => {
      currentDetail.value = { ...row }
      detailDialogVisible.value = true
    }


    // 审批
    const approve = async (row) => {
      try {
        await ElMessageBox.confirm('确认通过该客户申请吗？', '确认审批', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        })
        
        await approveCustomer(row.processInstanceId)
        ElMessage.success('审批通过成功')
        await refreshPendingList()
        await searchHistory()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审批通过失败:', error)
          ElMessage.error('审批通过失败')
        }
      }
    }

    // 拒绝
    const reject = async (row) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因：', '拒绝审批确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '拒绝原因不能为空',
          inputType: 'textarea',
          inputPlaceholder: '请输入拒绝原因'
        })
        
        await rejectCustomer(row.processInstanceId, reason)
        ElMessage.success('审批拒绝成功')
        await refreshPendingList()
        await searchHistory()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审批拒绝失败:', error)
          ElMessage.error('审批拒绝失败')
        }
      }
    }

    // 批量审批
    const batchApprove = async () => {
      if (selectedPendingItems.value.length === 0) {
        ElMessage.warning('请选择要审批的项目')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要批量审批选中的 ${selectedPendingItems.value.length} 个项目吗？`,
          '批量审批确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 批量调用审批API
        const promises = selectedPendingItems.value.map(item => 
          approveCustomer(item.processInstanceId)
        )
        
        await Promise.all(promises)
        ElMessage.success('批量审批成功')
        await refreshPendingList()
        await searchHistory()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量审批失败:', error)
          ElMessage.error('批量审批失败')
        }
      }
    }


    
    // 查看流程进度
    const viewProcessSteps = (row) => {
      selectedRecord.value = row
      processDialogVisible.value = true
    }
    
    // 关闭流程进度对话框
    const handleProcessDialogClose = () => {
      selectedRecord.value = null
      processDialogVisible.value = false
    }

    // 获取流程步骤 - 参考OrderDetail.vue的实现
    const getProcessSteps = (record) => {
      const steps = [
        { name: '销售员填写', status: 'completed' },
        { name: '地区经理审批', status: 'pending' },
        { name: '大区经理审批', status: 'pending' },
        { name: '信用控制组审批', status: 'pending' },
        { name: '销售总监审批', status: 'pending' },
        { name: '公司商务审核', status: 'pending' }
      ]
      
      // 根据记录类型获取当前步骤和审批结果
      let currentStep, approvalResult, approvalStatus
      
      if (record.approvalStep) {
        // 待审批记录或历史记录
        currentStep = record.approvalStep
        approvalResult = record.approvalResult
      } else if (record.currentStep) {
        // 我的申请记录
        currentStep = record.currentStep
        approvalStatus = record.approvalStatus
      }
      
      // 根据审批步骤确定当前进度
      const stepMapping = {
        'SALES_FILL': 0,
        'REGION_MANAGER_APPROVAL': 1,
        'AREA_MANAGER_APPROVAL': 2,
        'CREDIT_CONTROL_APPROVAL': 3,
        'SALES_DIRECTOR_APPROVAL': 4,
        'COMPANY_BUSINESS_APPROVAL': 5
      }
      
      const currentIndex = stepMapping[currentStep] || 0
      
      // 设置步骤状态
      for (let i = 0; i < steps.length; i++) {
        if (i < currentIndex) {
          steps[i].status = 'completed'
        } else if (i === currentIndex) {
          // 判断当前步骤的状态
          if (approvalResult === 'REJECTED' || approvalStatus === 'REJECTED') {
            steps[i].status = 'rejected'
          } else if (approvalStatus === 'APPROVED') {
            steps[i].status = 'completed'
          } else {
            steps[i].status = 'current'
          }
        } else {
          steps[i].status = 'pending'
        }
      }
      
      // 如果整个流程已完成，所有步骤都标记为完成
      if (approvalStatus === 'APPROVED') {
        steps.forEach(step => step.status = 'completed')
      }
      
      return steps
    }

    // 计算统计数据
    const calculateStatistics = () => {
      // 总审批数 = 历史已审批列表的行数
      const totalCount = historyList.value.length
      
      // 待审批数 = 待审批模块列表的行数
      const pendingCount = pendingList.value.length
      
      // 已通过和已拒绝数 = 历史已审批列表中按状态统计
      const approvedCount = historyList.value.filter(customer => 
        customer.approvalStatus === 'APPROVED'
      ).length
      
      const rejectedCount = historyList.value.filter(customer => 
        customer.approvalStatus === 'REJECTED'
      ).length
      
      // 审批中数量 = 历史已审批列表中审批中状态的数量
      const approvingCount = historyList.value.filter(customer => 
        customer.approvalStatus === 'APPROVING'
      ).length

      statistics.value = {
        totalApplications: totalCount,
        pendingApprovals: pendingCount,
        approvedApplications: approvedCount,
        rejectedApplications: rejectedCount,
        approvingApplications: approvingCount
      }
      
      console.log('统计数据更新:', statistics.value)
    }

    // 新建申请
    const createNewApplication = () => {
      // TODO: 跳转到新建申请页面
      ElMessage.info('跳转到新建申请页面')
    }

    // 编辑申请
    const editApplication = (row) => {
      // TODO: 跳转到编辑申请页面
      ElMessage.info(`编辑申请 ${row.id}`)
    }

    // 提交申请审批
    const submitApplication = async (row) => {
      try {
        await ElMessageBox.confirm('确认提交该客户申请进行审批吗？', '确认提交', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        await submitCustomerApplication(row.id)
        ElMessage.success('客户申请提交成功，已启动审批流程')
        await searchMyApplications()
        await refreshPendingList()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交申请失败:', error)
          ElMessage.error('提交申请失败')
        }
      }
    }

    // 撤销申请
    const cancelApplication = async (row) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入撤销原因：', '撤销申请确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '撤销原因不能为空'
        })
        
        await cancelCustomerApplication(row.id, reason)
        ElMessage.success('申请撤销成功')
        await searchMyApplications()
        await refreshPendingList()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('撤销申请失败:', error)
          ElMessage.error('撤销申请失败')
        }
      }
    }

    // 分页处理函数
    const handlePendingSizeChange = (val) => {
      pendingPagination.pageSize = val
      refreshPendingList()
    }

    const handlePendingCurrentChange = (val) => {
      pendingPagination.currentPage = val
      refreshPendingList()
    }

    const handleHistorySizeChange = (val) => {
      historyPagination.pageSize = val
      searchHistory()
    }

    const handleHistoryCurrentChange = (val) => {
      historyPagination.currentPage = val
      searchHistory()
    }

    const handleMyApplicationsSizeChange = (val) => {
      myApplicationsPagination.pageSize = val
      searchMyApplications()
    }

    const handleMyApplicationsCurrentChange = (val) => {
      myApplicationsPagination.currentPage = val
      searchMyApplications()
    }

    // 组件挂载时加载数据
    onMounted(async () => {
      await refreshPendingList()
      await searchHistory()
      calculateStatistics()
      await searchMyApplications()
    })

    return {
      activeTab,
      statistics,
      pendingList,
      pendingLoading,
      selectedPendingItems,
      pendingPagination,
      historyList,
      historyLoading,
      historySearchForm,
      historyPagination,
      myApplicationsList,
      myApplicationsLoading,
      myApplicationsSearchForm,
      myApplicationsPagination,
      processDialogVisible,
      selectedRecord,
      detailDialogVisible,
      currentDetail,
      processStepsDialogVisible,
      currentProcessDetail,
      processSteps,
      getApprovalStepTag,
      getApprovalStepName,
      getRoleTag,
      getRoleName,
      getApprovalResultTag,
      getApprovalResultName,
      getApprovalStatusTag,
      getApprovalStatusName,
      formatDate,
      getStepTimelineType,
      getStepIcon,
      getProcessSteps,
      calculateStatistics,
      handlePendingSelectionChange,
      refreshPendingList,
      searchHistory,
      resetHistorySearch,
      searchMyApplications,
      resetMyApplicationsSearch,
      viewDetail,
      viewProcessSteps,
      approve,
      reject,
      batchApprove,
      handleProcessDialogClose,
      createNewApplication,
      editApplication,
      submitApplication,
      cancelApplication,
      handlePendingSizeChange,
      handlePendingCurrentChange,
      handleHistorySizeChange,
      handleHistoryCurrentChange,
      handleMyApplicationsSizeChange,
      handleMyApplicationsCurrentChange,
      isOfficeBusiness
    }
  }
}
</script>

<style scoped>
.customer-approval {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.stats-info h3 {
  margin: 0 0 5px 0;
  font-size: 2rem;
  font-weight: bold;
}

.stats-info p {
  margin: 0;
  font-size: 0.9rem;
  opacity: 0.9;
}

.stats-icon {
  font-size: 3rem;
  opacity: 0.8;
}

.stats-primary {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
}

.stats-warning {
  background: linear-gradient(135deg, #E6A23C, #f0c78a);
}

.stats-success {
  background: linear-gradient(135deg, #67C23A, #95d475);
}

.stats-danger {
  background: linear-gradient(135deg, #F56C6C, #f89898);
}

.approval-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tab-content {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

.search-form .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 20px 0;
}

.process-steps-content {
  padding: 20px 0;
}

.process-info {
  margin-bottom: 30px;
}

.steps-timeline h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.step-content {
  padding: 10px 0;
}

.step-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.step-role,
.step-approver,
.step-comment,
.step-result {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.step-comment {
  font-style: italic;
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  margin-top: 8px;
}

.step-result {
  margin-top: 8px;
}

/* 流程进度样式 */
.process-progress {
  padding: 8px 0;
}

.progress-steps {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.progress-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  min-width: 60px;
}

.step-circle {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 4px;
  flex-shrink: 0;
}

.progress-step.completed .step-circle {
  background-color: #67C23A;
  color: white;
}

.progress-step.current .step-circle {
  background-color: #409EFF;
  color: white;
  animation: pulse 2s infinite;
}

.progress-step.rejected .step-circle {
  background-color: #F56C6C;
  color: white;
}

.progress-step.pending .step-circle {
  background-color: #E4E7ED;
  color: #909399;
}

.step-name {
  font-size: 10px;
  text-align: center;
  color: #606266;
  line-height: 1.2;
  max-width: 60px;
  word-break: break-all;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 表格样式优化 */
.el-table {
  border-radius: 6px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  font-weight: 600;
}

/* 标签页样式优化 */
:deep(.el-tabs__header) {
  margin: 0;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__item) {
  font-weight: 500;
  padding: 0 20px;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

/* 对话框样式优化 */
:deep(.el-dialog__header) {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 16px 20px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-approval {
    padding: 10px;
  }
  
  .toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-form {
    width: 100%;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .toolbar-right {
    justify-content: center;
  }
}
</style>
